package com.jams.goodox.activity.qa.teacher;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.BuildConfig;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.login.RegistActivity;
import com.jams.goodox.activity.login.RoleChooseActivity;
import com.jams.goodox.activity.qa.parent.UploadQuestionActivity;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.PhotoSelectUtils;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.ActionSheetDialog;
import com.jams.goodox.widget.ActionSheetDialog.OnSheetItemClickListener;
import com.jams.goodox.widget.ActionSheetDialog.SheetItemColor;
import com.jams.library.image.ImagePagerActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 * @author HP
 * @date 2018/5/18
 *
 * 教师回答问题
 * api/question/detail
 * api/answer/add
 *
 */

public class TeacherAnswerActivity extends BaseActivity {

    private static final String TAG = TeacherAnswerActivity.class.getSimpleName();

    @Bind(R.id.title)
    EditText title;
    @Bind(R.id.desc)
    EditText desc;

    @Bind(R.id.content)
    EditText content;

    @Bind(R.id.imageView)
    ImageView imageView;

    @Bind(R.id.submm_btn)
    TextView submm_btn;

    @Bind(R.id.indicate)
    TextView indicate;

    private String file;//文件路径
    private int questionId;//问题id
    private String imageUrl;
    private String price;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_teacheranswer;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "回答");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部
        questionId = getIntent().getIntExtra("questionId",-1);
        price = getIntent().getStringExtra("price");
//        getQuestionDetai();

        indicate.setVisibility(View.VISIBLE);
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                int countTx = 0;
                if(!TextUtils.isEmpty(s)){
                    countTx = s.length();
                    indicate.setText(countTx + "/150");
                }

            }
        });
    }

//    private void getQuestionDetai() {
//        clearMap();
//
//        params.put("requestData", "{" + "questionId:" + questionId + "}");
//        String strEntity = gson.toJson(params);
//        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);
//
//        showLoading();
//        Call<ResponseBody> example = createCallService(LoginService.class).questionDetail(body);
//
//        example.enqueue(new Callback<ResponseBody>() {
//            @Override
//            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                misLoading();
//                try {
//                    String data = response.body().string();
//                    Log.d(TAG, "getQuestionDetai data = " + data);
//
//                    JSONObject jsonObject = new JSONObject(data);
//
//                    if(200 == jsonObject.getInt("code")){
//                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));
//                        JSONObject object2 = new JSONObject(object.getString("question"));
//                        String title_tx = object2.getString("title");
//                        String descr_tx = object2.getString("descr");
//                        JSONArray imageList = object.getJSONArray("imageList");
//                        imageUrl = imageList.getString(0);
//                        title.setText(title_tx);
//                        desc.setText(descr_tx);
//                        Log.d(TAG,"imageList = " + imageUrl);
//                        Glide.with(TeacherAnswerActivity.this).load(imageUrl).into(imageView);
//
//                    }else {
//                        if(jsonObject.has("error")){
//                            ToastUtil.show("error:" + jsonObject.getString("error") );
//                        }else {
//                            ToastUtil.show("网络异常！" );
//                        }
//                    }
//                } catch (Exception e) {
//                    ToastUtil.show("Exception:" + e.getMessage());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ResponseBody> call, Throwable t) {
//                misLoading();
//                Log.d(TAG,"onFailure = " + t.getMessage());
//            }
//        });
//
//    }

    @OnClick({R.id.imageView,R.id.submm_btn})
    public void onClick(View view) {

        switch (view.getId()){
//            case R.id.imageView:
//                List<String> imageListNew = new ArrayList<>();
//                imageListNew.add(imageUrl);
//                Intent intent = new Intent(this,ImagePagerActivity.class);
//                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
//                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (Serializable) imageListNew);
//                break;

            case R.id.submm_btn:
                uploadAnswer();
                break;
        }
    }

    //提交问题
    private void uploadAnswer() {

        if(TextUtils.isEmpty(content.getText())){
            ToastUtil.show("请输入您的回答");
            return;
        }

        Map<String,RequestBody> params = new HashMap<>();
        params.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"), "test"));
        params.put("uuid", RequestBody.create(MediaType.parse("multipart/form-data"), "5617222222"));
        params.put("version", RequestBody.create(MediaType.parse("multipart/form-data"), BuildConfig.VERSION_NAME));
        params.put("accessToken", RequestBody.create(MediaType.parse("multipart/form-data"), SePref.getToken()));

        StringBuilder pData = new StringBuilder();
        pData.append("questionId:" + questionId)
                .append(",yangCoin:" + price)
                .append(",content:" + content.getText().toString());

        params.put("requestData", RequestBody.create(MediaType.parse("multipart/form-data"), "{" + pData.toString() + "}"));

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).addAnswer(params,null);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        ToastUtil.show("回答成功");
                        setResult(RESULT_OK);
                        finish();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }


}
